<script setup>
import { ref, reactive,onMounted } from "vue";
import { ElMessage, ElMessageBox ,ElLoading  } from "element-plus";
import {get_comment_info, add_comment_info, edit_comment_status, delete_comment} from "../../api/index";
import {useRouter} from "vue-router";
import { SERVER_HOST } from "../../config";
    const msg=ref("这是变量消息")
    const commentQuery = reactive({
      page: 0,
      rows: 10,
      id:'',
      news_id:'',
      user_id:'',
      content:'',
      status:'',
    });
    const addOrEditFrom = reactive({
      id:'',
      news_id:'',
      uid:'',
      content:'',
      status:'',
    })
    const editVisible =ref(false)       //编辑框开关
    let addVisible =ref(false)       //添加框开关
    const commentTableData = ref([]);   //表格数据
    const commentloadingSwicth = ref(false)  //表格loading开关
    const commentPageTotal = ref(0)   //页码总数

    // 删除评论
    const remove_comment = (index,row) => {
        ElMessageBox.confirm("确定要删除吗？", "提示", {
          type: "warning",
        }).then(() => {
          Object.keys(addOrEditFrom).forEach((item) => {
            addOrEditFrom[item] = row[item];
          });
          delete_comment(addOrEditFrom).then((res) => {
            var code = res.code;
            var msg = res.msg;
            if (code===200){
              ElMessage.success(""+msg);
            }else if(code===401){
              ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
                confirmButtonText: "确定",
                callback: action => {
                  router.push('/login')
                }
              });
            }else {
              ElMessage.error(''+msg);
            }
          });
          //停留200毫秒后刷新页面数据
          setTimeout(() => {
            getCommentData()
          }, 200);
        }).catch(() => {
          ElMessage.warning("删除取消");
        });
    };


    // 获取表格数据
    const getCommentData = () => {
      var startTime= new Date().getTime();
      commentloadingSwicth.value=true;
      get_comment_info(commentQuery).then((res) => {
        var code = res.code;
        if (code===200){
          commentTableData.value = res.data;
          commentPageTotal.value = res.total || 0;
          console.log(res.data[0].headline)
          var endTime= new Date().getTime();
          ElMessage.success('请求耗时'+(endTime-startTime)+"ms");
          commentloadingSwicth.value=false;
        }else if(code===401){
          ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
            confirmButtonText: "确定",
            callback: action => {
              sessionStorage.clear()
              localStorage.removeItem("user_name");
              localStorage.removeItem("token");
              console.log('用户信息已清除')
              router.push('/login')
            }
          });
        }else{
          commentTableData.value = res.data;
          commentloadingSwicth.value=false;
        }

      }

  );

};
    // 刷新表格数据
    const refresh=()=>{
          commentQuery.id=''
          commentQuery.news_id=''
          commentQuery.user_id=''
          commentQuery.content=''
          commentQuery.status=''
          getCommentData()
    }
    //分页导航
    const commentHandlePageChange = (val)=>{
      commentQuery.page = val-1;
      getCommentData();
    }
    const commentHandleSizeChange = (val)=>{
      commentQuery.rows = val;
      getCommentData();
    }
    //控制添加评论弹框
    const addComment =()=>{
      addOrEditFrom.id=''
      addOrEditFrom.status = ''
      addOrEditFrom.news_id = ''
      addOrEditFrom.uid = ''
      addOrEditFrom.content = ''
      addVisible.value = true
    }
    //控制编辑评论弹框
    const editComment =(index,row)=>{

      Object.keys(addOrEditFrom).forEach((item) => {
        addOrEditFrom[item] = row[item];
      });
      if (addOrEditFrom.status===1){
        addOrEditFrom.status="正常"
      }else if (addOrEditFrom.status===0){
        addOrEditFrom.status="下架"
      }
      console.log(addOrEditFrom.status)
      editVisible.value = true;
    }

// 获取视口高度
const screenHeight = window.innerHeight-290;
    // 保存编辑
    const saveEdit = ()=>{
        // 发送编辑请求
      // 发送添加请求
      if (addOrEditFrom.status===""){
        ElMessage.warning("关联的新闻id不能为空！");
      }else{
        edit_comment_status(addOrEditFrom).then((res) => {
          var code=res.code
          if (code===200){
            ElMessage.success(''+res.msg);
            editVisible.value = false;
            addOrEditFrom.news_id=""
            addOrEditFrom.uid=""
            addOrEditFrom.content=""
            addOrEditFrom.status=""

          }else if(code===401){
            ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
              confirmButtonText: "确定",
              callback: action => {
                router.push('/login')
              }
            });
          }else {
            ElMessage.error(''+res.msg)
          }
          getCommentData()


        });
      }
    }
    // 保存添加
    const saveAdd = ()=>{
      // 发送添加请求
      if (addOrEditFrom.news_id===""){
        ElMessage.warning("关联的新闻id不能为空！");
      }else if (addOrEditFrom.content===""){
        ElMessage.warning("评论内容不能为空！");
      }else if (addOrEditFrom.uid===""){
        ElMessage.warning("用户id不能为空！");
      }
      else{
        add_comment_info(addOrEditFrom).then((res) => {
          var code=res.code
          if (code===200){
            ElMessage.success(''+res.msg);
            addVisible.value = false;
            addOrEditFrom.news_id=""
            addOrEditFrom.uid=""
            addOrEditFrom.content=""

          }else if(code===401){
            ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
              confirmButtonText: "确定",
              callback: action => {
                router.push('/login')
              }
            });
          }else {
            ElMessage.error(''+res.msg)
          }
          getCommentData()


        });
      }
    }
    onMounted(()=>{
      getCommentData()
    })
</script>

<template>
      <div>
        <div class="container"  >
          <div class="handle-box" >
            <el-input v-model="commentQuery.id" placeholder="评论id" clearable class="handle-input mr10"></el-input>
            <el-input v-model="commentQuery.news_id" placeholder="新闻id" clearable class="handle-input mr10"></el-input>
            <el-input v-model="commentQuery.content" placeholder="评论内容关键词" clearable class="handle-input mr10"></el-input>
            <el-select v-model="commentQuery.status" placeholder="评论状态" clearable class="handle-select mr10">
              <el-option key="1" label="正常" value="1"></el-option>
              <el-option key="0" label="下架" value="0"></el-option>
            </el-select>
            <el-button type="primary" icon="el-icon-search" @click="getCommentData">搜索</el-button>
            <el-button type="primary" @click="addComment" icon="el-icon-circle-plus-outline" >新增</el-button>
            <el-button type="danger" icon="el-icon-delete" >批量删除</el-button>
            <el-button type="primary" icon="el-icon-refresh" @click="refresh" >刷新</el-button>
          </div>
          <el-table :data="commentTableData" v-loading="commentloadingSwicth"  element-loading-text="拼命加载中..." element-loading-background="rgba(250,250,250,0.97)" border class="table" :height="screenHeight" ref="multipleTable" header-cell-class-name="table-header">
            <el-table-column  prop="id" label="评论id"></el-table-column>
            <el-table-column prop="news_id" label="新闻id"></el-table-column>
            <el-table-column prop="content" label="评论内容"></el-table-column>
            <el-table-column prop="uid" label="uid"></el-table-column>
            <el-table-column prop="create_time" label="发布时间"></el-table-column>
            <el-table-column  label="评论状态" align="center">
              <template #default="scope">
                <el-tag  :type="scope.row.status===1?'success':'danger'" effect="dark">{{scope.row.status===1?'正常':'下架'}}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button type="text" icon="el-icon-edit" @click="editComment(scope.$index, scope.row)" >编辑 </el-button>
                <el-button type="text" icon="el-icon-delete" class="red" @click="remove_comment(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background layout="total, prev, sizes, pager, next,jumper"
                           :current-page="commentQuery.page+1"
                           :page-size="commentQuery.rows"
                           :total="commentPageTotal"
                           :page-sizes="[5, 10, 20, 50, 100]"
                           @current-change="commentHandlePageChange"
                           @size-change="commentHandleSizeChange">

            </el-pagination>
          </div>


          <!--   编辑框      -->
          <el-dialog title="编辑评论" v-model="editVisible" width="35%">
            <el-form label-width="70px">
              <el-form-item label="评论id" width="50%">
                <el-input v-model="addOrEditFrom.id" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="评论状态">
                <el-select v-model="addOrEditFrom.status" placeholder="状态" class="handle-select mr10">
                  <el-option key="1" label="正常" value="1"></el-option>
                  <el-option key="0" label="下架" value="0"></el-option>
                </el-select>
                <el-tag  :type="addOrEditFrom.status==='正常'?'success':'danger'" effect="dark">
                  {{ addOrEditFrom.status==='正常'?'正常':'下架' }}</el-tag>
              </el-form-item>
            </el-form>
            <template #footer >
                <span class="dialog-footer" >
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">保存</el-button>
                </span>
            </template>
          </el-dialog>

          <!--   新增框      -->
          <el-dialog title="新增评论" v-model="addVisible" width="35%">
            <el-form label-width="70px">
              <el-form-item label="新闻id" width="50%">
                <el-input v-model="addOrEditFrom.news_id" ></el-input>
              </el-form-item>
              <el-form-item label="评论内容" width="50%">
                <el-input v-model="addOrEditFrom.content" ></el-input>
              </el-form-item>
              <el-form-item label="用户id" width="50%">
                <el-input v-model="addOrEditFrom.uid" ></el-input>
              </el-form-item>
            </el-form>
            <template #footer >
                <span class="dialog-footer" >
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveAdd">保存</el-button>
                </span>
            </template>
          </el-dialog>
        </div >


      </div>
</template>



<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 240px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 5px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
